package com.example.demo.utils;





import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author: YinLei
 * Package:  com.englishcode.fastdfsdemo.utils
 * @date: 2021/6/18 10:03
 * @Description: Fastdfs客户端工具类
 * @version: 1.0
 */
@Component
public class FdfsClientUtils {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;


    public String upload(MultipartFile myfile) throws Exception{
        //文件名
        String originalFilename = myfile.getOriginalFilename().substring(myfile.getOriginalFilename().lastIndexOf(".") + 1);
        // 文件扩展名
        String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());

        StorePath storePath = fastFileStorageClient.uploadImageAndCrtThumbImage(myfile.getInputStream(), myfile.getSize(),originalFilename , null);

        String path = storePath.getFullPath();

        return path;
    }


    /**
     * 下载文件
     *
     * @param filePath 文件路径
     * @return 文件字节
     * @throws IOException
     */
    public byte[] downloadFile(String filePath) throws IOException {
        byte[] bytes = null;
        if (!StringUtils.isEmpty(filePath)) {
            String group = filePath.substring(0, filePath.indexOf("/"));
            String path = filePath.substring(filePath.indexOf("/") + 1);
            DownloadByteArray byteArray = new DownloadByteArray();
            bytes = fastFileStorageClient.downloadFile(group, path, byteArray);
        }
        return bytes;
    }

    /**
     * 删除文件
     *
     * @param filePath 文件路径
     */
    public void deleteFile(String filePath) {
        if (!StringUtils.isEmpty(filePath)) {
            fastFileStorageClient.deleteFile(filePath);
        }
    }



}

